"use strict";

var C = require('../common'),
    mysql = require('mysql');

var MySqlService = function (owner, config) {
    var pools = {}; // Active Pools
    var self = this;

    this.connStr = function (name) {
        config[name] || C.throwRequired('[' + owner.stack + '].mysql.[' + name + ']');
        return config[name].connection;
    };

    this.connect = function(name, callback) {
        var pool;

        if (name in pools) {
            pool = pools[name];
        } else {
            var conn = self.connStr(name);
            conn || C.throwRequired('[' + owner.stack + '].mysql.[' + name + '].connection');

            pool = mysql.createPool(conn);
            pools[name] = pool;
        }

        pool.getConnection(callback);
    };
};

module.exports = {

    type: 'service',

    load: function (owner, dbs, cb) {

        var service = new MySqlService(owner, dbs);
        owner.registerService('mysql', service);

        cb();
    }
};


